<template>
  <div class="contentBox">
    <div class="search">
     
      
      <!-- 搜索 -->
      <HostSearchForm @search="handleSearch" @reset="handleReset" class="search">
        <template #search-content>
          <el-form-item :label="'类型：'">
            <el-select allow-create filterable v-model="searchSelect" style="width:200px" placeholder="请选择标签">
              <el-option v-for="item in array" :key="item.val" :label="item.val" :value="item.val">
                <span style="float: left">{{ item.val }}</span>
                <span
                  style="
                    float: right;
                    color: var(--el-text-color-secondary);
                    font-size: 13px;
                  "
                >
                  {{ item.num }}
                </span>
              </el-option>

            </el-select>
          </el-form-item>
            
          
        </template>
      </HostSearchForm>
    </div>
    <div class="header">
      <div>
        <el-button class="button" type="" @click="addScript">新建脚本</el-button>
        <el-button @click="goTag">标签</el-button>
      </div>
      <el-input
      v-model="input"
      style="max-width: 600px"
      placeholder="Please input"
      class="input-with-select"
      :suffix-icon="Search"
    >
      <template #prepend>
        <el-select v-model="select" placeholder="Select" style="width: 115px">
          <el-option label="Restaurant" value="1" />
          <el-option label="Order No." value="2" />
          <el-option label="Tel" value="3" />
        </el-select>
      </template>
    </el-input>
    </div>
    
    <KyTable 
        ref="tableRef" 
        :getData="getScriptList" 
        :showSelect="showSelect"
      >
        <template #table-action>
          <div class="os-upgrade-table-action">
            <!-- 批量操作 -->
            <el-dropdown>
              <el-button class="kylin-item-button" :disabled="$refs.tableRef && $refs.tableRef.selectRow.rows.length == 0">
                批量操作<el-icon><ArrowDown /></el-icon>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu v-show="$refs.tableRef && $refs.tableRef.selectRow.rows.length !== 0">
                  <el-dropdown-item v-for="item in allActionOptions" :key="item.value" :value="item.value" @click.stop="handlePopConfirm(item)">
                    {{item.label}}
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
            <!-- 设置 -->
            <el-button class="kylin-item-button" @click.stop="handleCustomColumn" name="plugin-os-upgrade:operation">
              <el-icon><Setting /></el-icon>
            </el-button>
          </div>
        </template>
        <!-- table表格 -->
        <template #table>
          <el-table-column
            prop="name"
            :label="'脚本名称'"
          />
          <el-table-column
            prop="script_type"
            :label="'脚本语言'"
          />
          <el-table-column
            prop="tag"
            :label="'场景标签'"
          >
            <template #default="scope">
                <span class="tag">{{ scope.row.tag.name }}</span>
              <el-button
                @click.prevent="editScript(scope.row)"
                link
                size="medium"
                class="el-icon-edit label-edit"
              ><el-icon><EditPen /></el-icon>
              </el-button>
            </template>
          </el-table-column>
          <!-- <el-table-column
            prop="targetSystem"
            :label="'被引用'"
          />
          <el-table-column
            prop="targetSystem"
            :label="'线上版本'"
          /> -->
          <el-table-column
            prop="modify_user"
            :label="'更新人'"
          />
          <el-table-column
            prop="modify_time"
            :label="'更新时间'"
          />
          <el-table-column
            prop="usage_type"
            :label="'使用类型'"
          />
          <el-table-column
            prop="targetSystem"
            :label="'操作'"
          >
            <template #default="scope" >
              <el-button type="link" size="small" @click="goVersion(scope.row)">版本管理</el-button>
              <el-button type="link" size="small">去执行</el-button>
              <el-button type="link" size="small" @click="editScript(scope.row)">编辑</el-button>
              <el-button type="link" size="small" @click="deleteScript(scope.row)">删除</el-button>
            </template>

          </el-table-column>
        </template>
        
        <template #empty>
          <div>
            <span role="button" class="link-btn" @click="addScript">
              创建一个脚本吧!
            </span>
          </div>
        </template>
    </Kytable>
    
    <el-dialog
        :title="dialogTitle"
        v-model="dialogVisible"
        :before-close="handleCloseDialog"
        :width="dialogWidth"
      >
        <CustomColumn
            v-if="rwType === 'custom_list'"
            @click="handleCloseDialog"
            :customData="colData"
            :rawData="rawData"
            @handleOk="handleCustomColumnOk"
          ></CustomColumn>
          <EditTag v-if="rwType === 'edit_tag'" :script-data="currentScriptData" @update="handleUpdate" @close="handleCloseDialog" ></EditTag>
          <EditScriptInfo 
            v-if="rwType === 'edit_script'"
            :script-data="currentScriptData"
            @update="handleUpdate"
            @close="handleCloseDialog"
          ></EditScriptInfo>
    </el-dialog>
  </div>
</template>
<script lang="ts" setup>
import { ref,defineAsyncComponent } from 'vue'
import { useRouter } from 'vue-router'
import { Search } from '@element-plus/icons-vue'
import { getScriptList,seriptDel } from '@/api/scriptLibrary';
import { ElMessageBox, ElMessage } from 'element-plus';
const KyTable = defineAsyncComponent(() => import('@/components/KyTable/index.vue'));
const CustomColumn = defineAsyncComponent(() => import('@/components/customColumn/index.vue'));
const EditTag = defineAsyncComponent(() => import('./editTag.vue'));
const HostSearchForm  = defineAsyncComponent(() => import( '@/components/HostSearchForm.vue'));
const EditScriptInfo  = defineAsyncComponent(() => import( './EditScriptInfo.vue'));
const router = useRouter();
const searchSelect = ref<string>('全部脚本')
const array = [{val:'全部脚本',num:20},{val:'未分类',num:10},{val:'测试',num:2}]
const dialogVisible = ref<boolean>(false);
const dialogTitle = ref<string>('自定义列');
const dialogWidth = ref<string>('50%');
const rwType = ref<string>('custom_list');
const  colData = ref<any>([]);
const rawData = ref<any>([]);

const tableRef =  ref(null);
const input = ref('')
const select = ref('')


const showSelect = ref<boolean>(true);

const allActionOptions = [
  {label: '去执行', value:'creatGroup'},
]
interface SearchCriteria {
  type: string;
}
const searchCriteria = ref<SearchCriteria>({
  type: searchSelect.value
});

const handleSearch = () => {
  searchCriteria.value = {
    type: searchSelect.value
  };
};

function handleReset() {
  searchSelect.value = '';
  searchCriteria.value = {
    type: '',
  };
  tableRef.value?.resetSearch();
}

const addScript = () => { 
  router.push('/script_library/addScript')
}
const editScript = (row: any) => {   
  // 检查脚本数据中是否有 id 字段
  if (row && row.id) {
    console.log('编辑脚本', row);
    currentScriptData.value = row;
    dialogVisible.value = true;
    rwType.value = 'edit_script';
    dialogTitle.value = '编辑脚本';
    dialogWidth.value = '40%';
  } else {
    ElMessage.warning('无效的脚本数据');
  }
}

const currentScriptData = ref<any>(null);
const editTag = (row:any) => {   
  console.log('编辑标签', row)
  currentScriptData.value = row;
  dialogVisible.value = true;
  rwType.value = 'edit_tag';
  dialogTitle.value = '编辑标签';
  dialogWidth.value = '40%';
}

const handleCustomColumn = (row: any) => {
  // console.log('[ 自定义列 ] >', '自定义列');
    getCustomColumnFun()
    rwType.value = 'custom_list';
    dialogVisible.value = true;
    dialogTitle.value = '自定义列';
};

const getCustomColumnFun = async( ) => {
  
  colData.value = [
    { name: 'action', label: '脚本名称1111' },
    { name: 'ip', label: '脚本语言' },
    { name: 'originalSystem', label: '场景标签' },
    { name: 'targetSystem', label: '被引用' },
    { name: 'targetSystem', label: '线上版本' },
    { name: 'targetSystem', label: '更新人' },
    { name: 'targetSystem', label: '更新时间' },
  ]
  // const userId = getUserId()
  //   if (userId) {
  //     const res = await getCustomColumn(userId)
  //     if (res.data.data && res.data.data.length == rawData.value.length && res.data.data[res.data.data.length - 1].name == 'groupName') {
  //       colData.value = res.data.data;
  //     } else {
  //       colData.value = rawData;
  //     }
  //   } else {
  //     colData.value = rawData;
  //   }
}
const handlePopConfirm =async (row: any,type?:string) => {
      // dialogTitle.value = t('point')
      console.log('[ row.value ] >', row.value)
}
const handleCloseDialog = () => {
  dialogVisible.value = false;
  rwType.value = '';
};
const handleCustomColumnOk = (val: any) => {
  console.log(val);
  handleCloseDialog();
}

const handleUpdate = () => {
  // 更新成功后刷新表格数据
  tableRef.value?.refresh();
};
const goTag = () => {
  router.push('/script_library/tag')
}

// 删除脚本函数
const deleteScript = (row: any) => {
  // 弹出确认对话框
  ElMessageBox.confirm(
    `确定要删除脚本 "${row.name}" 吗？此操作不可撤销。`,
    '确认删除',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  )
    .then(async () => {
      try {
        // 调用删除接口
        const res = await seriptDel({ id: row.id });
        if (res.data.code === 200) {
          // 显示成功消息
          ElMessage.success('脚本删除成功');
          // 刷新表格数据
          tableRef.value?.refresh();
        } else {
          ElMessage.error(res.data.msg || '脚本删除失败');
        }
      } catch (error) {
        console.error('删除脚本失败:', error);
        ElMessage.error('脚本删除失败');
      }
    })
    .catch(() => {
      // 用户取消删除
      ElMessage.info('已取消删除');
    });
}
// 版本管理
const goVersion = (row: any) => {
  console.log('[ row ] >', row)
  // 将row对象转换为适合query参数的格式，特别处理tag对象
  const queryParams = { ...row };
  // 如果row.tag是对象，将其序列化为JSON字符串
  if (row.tag && typeof row.tag === 'object') {
    queryParams.tag = JSON.stringify(row.tag);
  }
  router.push({
    path: '/script_library/version',
    query: queryParams
  })
}
</script>
<style scoped lang="scss">
.search{
  margin-top: 20px;
}
.contentBox{
  width: auto;
}
.header{
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
  .inputSearch{
    width: 200px;
  };
}
.selectdiv{
  display: flex;
  align-items: center;


}

.tag {
  display: inline-block;
  padding: 0 5px;
  margin: 2px;
  line-height: 20px;
  font-size: 12px;
  color: #409eff;
  background-color: #ecf5ff;
  border: 1px solid #d9ecff;
  border-radius: 4px;
}

</style>